// pages/i/pay-qrcode.js
const auth = require('../../utils/auth.js')
const UserService = require('../../services/user.js')
const BizService = require('../../services/biz.js')
const bizPayService = require('../../services/bizPay.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: null,
        customerInfo: null,
        isLoggedIn: false,
        userInfo: null,
        loginReady: false, // 登录是否准备完成
        bizInfo: null,
        payPrice: 0,// 输入金额
        payMoney: 0,// 实付金额

        discount: 0, // 折扣比例，如70表示70%
        discount_txt: '', // 折扣文本
        hasDiscount: false, // 是否有折扣
        customerScoreTotal: 0,// 顾客总云豆余额
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(query) {
        // 1. 解析 code
        let q = decodeURIComponent(query.q || '');
        q = decodeURIComponent(q);
        let id = null;
        try {
            const urlObj = new URL(q);
            id = urlObj.searchParams.get('id');
        } catch (e) {
            const match = q.match(/[?&]id=([^&]+)/);
            if (match) id = match[1];
        }
        this.setData({ id });

        this.checkLoginStatus()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        // 页面显示时检查登录状态
        if (this.data.loginReady == false) {
            this.checkLoginStatus();
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    async loadUserBalance() {
        try {
            const result = await bizPayService.getBalance({
                biz_id: this.data.bizInfo.id,
                user_id: this.data.userInfo.id
            })

            if (result.success) {
                const discount = result.data.discount
                const hasDiscount = discount && discount > 0 && discount < 100


                this.setData({
                    discount: discount,
                    discount_txt: result.data.discount_txt,
                    hasDiscount: hasDiscount,
                    customerScoreTotal: result.data.user_total_score
                })
            } else {
                wx.showToast({
                    title: result.message,
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('加载云豆余额失败:', error)
            wx.showToast({
                title: '获取云豆余额失败',
                icon: 'none'
            })
        }
    },


    /**
       * 检查登录状态
       */
    async checkLoginStatus() {
        try {
            const loginStatus = await auth.checkLoginStatus()
            console.log(loginStatus)
            this.setData({
                isLoggedIn: loginStatus.isLoggedIn,
                userInfo: loginStatus.userInfo,
                loginReady: true
            })

            if (loginStatus.isLoggedIn) {
                // 加载用户信息
                this.getPayQrcodeRecord();
            }
        } catch (error) {
            this.setData({
                isLoggedIn: false,
                userInfo: null,
                loginReady: true
            })
        }
    },

    /**
     * 自动登录完成回调
     * 由app.js调用
     */
    onAutoLoginComplete(isLoggedIn, userInfo) {
        this.setData({
            isLoggedIn: isLoggedIn,
            userInfo: userInfo,
            loginReady: true
        });

        if (isLoggedIn) {
            this.getPayQrcodeRecord()
        }
    },

    async getPayQrcodeRecord() {
        const result = await BizService.payQrcodeRecord({
            id: this.data.id,
            showLoading: true,
            needAuth: true,
        });

        if (result.success) {
            this.setData({
                bizInfo: result.data.biz,
                customerInfo: result.data.customer,
            }, function () {
                this.loadUserBalance()
            })
        }
    },

    /**
   * 支付金额输入
   */
    onPayPriceInput(e) {
        const inputValue = e.detail.value
        let payPrice = parseFloat(inputValue)
        this.setData({
            payPrice: payPrice
        })

        this.calculatePayPlan()
    },

    calculatePayPlan() {
        const payPrice = this.data.payPrice
        const discount = this.data.discount
        const hasDiscount = this.data.hasDiscount
        let payMoney = payPrice
        if (hasDiscount) {
            payMoney = (payPrice * discount / 100).toFixed(2)
        }

        if (payMoney > this.data.customerScoreTotal) {
            this.setData({
                payMoney: 0,
                payPrice: 0
            }, function () {
                wx.showToast({
                    title: '顾客云豆余额不足，请重新输入',
                    icon: 'none'
                })
            })

            return;
        }

        this.setData({
            payMoney: payMoney
        })
    },

    async startPay() {
        wx.showLoading({
            title: '收款中...',
            mask: true
        })

        const result = await bizPayService.startPayFromBiz({
            pay_qrcode_record_id: this.data.id,
            pay_price: this.data.payPrice,
            user_id: this.data.userInfo.id,
            biz_id: this.data.bizInfo.id
        })

        if (result.success) {
            wx.hideLoading()
            wx.showToast({
                title: '收款成功',
                icon: 'success'
            })
        } else {
            wx.hideLoading()
            wx.showToast({
                title: result.message,
                icon: 'none'
            })
        }
    }
})